/* 首页 */
import api from '../../utils/http'
let amapFile = require('../../libs/amap-wx.js') //引入高德地图api
let WebIM = require('../../utils/WebIM.js').default

let app = getApp(),  pageStart = 1

Page({
  data: {
    showDialog: false,  //是否显示登陆对话框，默认不显示
    dialogFlag: false,  //用户默认未登录
    locationFlag: false,  //授权地理位置
    games: [],  //游戏导航
    manito: [], //附近大神
    newPerson: [],  // 新人报到
    guessLike: [],  //猜你喜欢

    isIphoneX: app.globalData.isIphoneX,
		requesting: false,
		end: false,
		emptyShow: false,
		page: pageStart,
		hasTop: false,
    enableBackToTop: false,
		refreshSize: 90,
		bottomSize: 0,
		color: "#1ca0ff",
    lastPage: ''  //总页数
  },
 
  onLoad() {
    this.setData({
      locationFlag: wx.getStorageSync('city') ? true : false,
      dialogFlag: wx.getStorageSync('token') ? true : false
    })
    // 初始化后，执行一次下拉刷新
    this.getList('refresh', pageStart);
    
  },

  onShow() {
    // 登录环信
    let options = { 
      apiUrl: WebIM.config.apiURL,
      user: wx.getStorageSync('userId'),
      pwd: '123456',
      grant_type: 'password',
      appKey: WebIM.config.appkey
    }
    WebIM.conn.open(options)

  },

  onReady(){
    // 授权地址位置
    this.getUserLocation()
    
  },

  // 首页游戏导航
  getGameList() {
    api.getGameList().then(res => {
      let result = res.data.data
      console.log('首页游戏导航', result) 

      this.setData({games: result.slice(0, 7)})
    })
  },

  // 跳转方法
  jump(e){
    if(!this.data.dialogFlag){
      this.setData({showDialog: true})
    }else{
      switch(e.currentTarget.dataset.name){
        case 'search':
          wx.navigateTo({url: '/pages/search/search'})
          break
        case 'game':
          wx.navigateTo({url: `/pages/game/game?game_id=${e.currentTarget.id}`})
          break
        case 'more':
          wx.navigateTo({url: '/pages/more/more'})
          break
        case 'skill':
          wx.navigateTo({ url: `/pages/skill/skill?id=${e.currentTarget.id}` })
          break
        case 'nearPlayer':
          wx.navigateTo({ url: '/pages/nearPlayer/nearPlayer' })
          break
        case 'newPerson':
          wx.navigateTo({ url: '/pages/newPerson/newPerson' })
          break
        default:
          wx.navigateTo({url: '/pages/user/codeLogin/codeLogin'})
          break
      }
    }
  },

  // 去登录
  toLogin(){
    wx.navigateTo({url: '/pages/user/codeLogin/codeLogin'})
  },

  //附近大神
  nearPlayer() {
    let city = wx.getStorageSync('city')
    let params = city ? { type: 2, city: city } : { type: 1 }
    api.getNearPlayer(params).then(res => {
      let result = res.data.data
      console.log('附近大神', result)

      this.setData({manito: result?result.slice(0, 5):[]})
    })

  },

  // 最新大神
  getNewPerson() {
    api.getNewPerson({ type: 1, page: this.data.page }).then(res => {
      console.log('最新大神', res.data.data)
      this.setData({ newPerson: res.data.data, guessLike: res.data.data, lastPage: res.data.meta.last_page })

    })
  },

  // 授权地址位置
  getUserLocation() {
    let that = this
    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',  
            success: () => {
              wx.getLocation({
                type: 'gcj02',
                success: res => {
                  //调用高德地图api
                  let myAmapFun = new amapFile.AMapWX({key: 'a5c4908e0cfa4038e4b4653258cd85ce'})
                  myAmapFun.getRegeo({
                    location: '' + res.longitude + ',' + res.latitude + '', //location的格式为'经度,纬度'
                    success(data) {
                      let city = data[0].regeocodeData.addressComponent.city //获取城市名
                      console.log('用户当前所在城市:', city)
                      wx.setStorage({key: 'city', data: city.slice(0,city.length-1)})

                      //附近大神
                      that.nearPlayer() 
                    }
                  })
                }
              })
            }
          })
        }
      }
    })
  },

	getList(type, currentPage) {
		this.setData({
			requesting: true
		})

		// 模拟异步获取数据场景
		setTimeout(() => {
			this.setData({
        requesting: false
			})

			if (type === 'refresh') {
				this.setData({
          page: currentPage,
          end: false
        })
        
        this.getGameList()  // 首页游戏导航 
        this.getNewPerson() // 最新大神
        this.nearPlayer() //附近大神

			} else {
        // 请求到最后一页的数据了
        if (currentPage > this.data.lastPage){
          this.setData({end: true})
          return false
        }

        // 猜你喜欢
        api.getNewPerson({ type: 1, page: currentPage}).then(res => {
          let result = res.data.data
          console.log('最新大神', res.data)

          this.setData({
            guessLike: [...this.data.guessLike, ...result],
            page: currentPage
          })
        })
			}

    }, 1000);
	},
	// 下拉刷新
	refresh() {
		this.getList('refresh', pageStart);
	},
	// 上拉加载
	more() {
		this.getList('more', this.data.page + 1);
	}
})